package com.yly.common.util;

import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Controller获取当前用户信息封转类
 * @author anqinghang
 * @since 2024/9/12 下午10:01
 */
@Data
@Component
@RequestScope
public class UserContextUtils {
  private String userId;
  private String userName;
  private Long roleId;
  private Long groupId;

  @Autowired
  public UserContextUtils() {
    HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(
        RequestContextHolder.getRequestAttributes())).getRequest();
    this.userId = request.getHeader("UserId");
    this.userName = request.getHeader("UserName");

    try {
      String roleIdStr = request.getHeader("roleId");
      this.roleId = roleIdStr != null ? Long.parseLong(roleIdStr) : null;
    } catch (NumberFormatException e) {
      this.roleId = null;
    }

    try {
      String groupIdStr = request.getHeader("groupId");
      this.groupId = groupIdStr != null ? Long.parseLong(groupIdStr) : null;
    } catch (NumberFormatException e) {
      this.groupId = null;
    }
  }
}